import 'dart:convert';

import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/settings_dao.dart';
import 'package:changxindianzishangwu/dao/user_info_dao.dart';
import 'package:changxindianzishangwu/db/ec_cache.dart';
import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/pages/find/find_page.dart';
import 'package:changxindianzishangwu/pages/my/settings/bind_phone_page.dart';
import 'package:changxindianzishangwu/pages/my/settings/settings_page.dart';
import 'package:changxindianzishangwu/provider/user.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/app_string.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/event_bus.dart';
import 'package:changxindianzishangwu/util/head_url.dart';
import 'package:changxindianzishangwu/util/show_custom_bottom_sheet.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/common_page.dart';
import 'package:changxindianzishangwu/widget/loding.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

import 'collect_page.dart';
import 'data_center_page.dart';
import 'feed_back_page.dart';

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> with AutomaticKeepAliveClientMixin {
  UserInfo _userInfo = getUserInfo();

  bool isOnline = false;

  @override
  void initState() {
    _initEvent();
    super.initState();
    Future.delayed(
        Duration.zero,
            (){
              getHintDialog(
               context,

          );
        }
    );

  }


  Future<V2TimUserFullInfo> getData() async {
    print("=====================" + EcCache.getInstance().get('userId'));
    V2TimValueCallback<List<V2TimUserFullInfo>> infos = await TencentImSDKPlugin
        .v2TIMManager
        .getUsersInfo(userIDList: [EcCache.getInstance().get('userId')]);
    if (infos.code == 0) {
      Provider.of<UserModel>(context, listen: false).setInfo(infos.data[0]);
      return infos.data[0];
    }
    return null;
  }

  var flag = false;
  V2TimUserFullInfo info;

  @override
  Widget build(BuildContext context) {

    return FutureBuilder(
      future: getData(),
      builder: (context, sp) {
        if (sp.connectionState != ConnectionState.done) {
          return CommonPage.loading(() {});
        } else {
          // V2TimValueCallback<List<V2TimUserFullInfo>> infos=sp.data;
          if (sp.hasData) {
            info = sp.data;
            return Scaffold(
              appBar: AppBar(
                elevation: 0,
                toolbarHeight: height(40),
              ),
              body: Container(
                child: Column(
                  children: <Widget>[
                    _userInfoWidget(info),
                    SizedBox(
                      height: 10,
                    ),
                    _item("images/图片.png", "我的动态", () {
                      Get.to(() => FindPage(
                            "${getUserInfo().userId}",
                            isOnlyUser: true,
                          ));
                    }),
                    SizedBox(
                      height: 10,
                    ),
                    _item("images/ic_data_center.png", "数据中心", () {
                      Get.to(() => DataCenterPage());
                    }),
                    _item("images/档案.png", "收藏", () {
                      Get.to(() => CollectPage());
                    }),

                    ///7.31 先行隐藏
                    // _item("images/分享.png", "分享", () {}),
                    _item("images/说明.png", "意见反馈", () {
                      Get.to(() => FeedBackPage("意见反馈"));
                    }),
                    _item("images/设置.png", "设置", () {
                      Get.to(() => SettingsPage()).then((value) {
                        if (isOnline && mounted) {
                          setState(() {
                            _userInfo = getUserInfo();
                          });
                        }
                      });
                    }),
                  ],
                ),
              ),
            );
          } else {
            return Column(
              children: [
                Expanded(
                  flex: 1,
                  child: SizedBox(),
                ),
                Expanded(
                  flex: 3,
                  child: CommonPage.loading(() {
                    EcCache.getInstance().clear();
                    Get.offAllNamed("/loginInit");
                  }, title: "登录失效", state: PageState.PAGE_ERROR),
                ),
                Expanded(
                  flex: 1,
                  child: SizedBox(),
                ),
              ],
            );
          }
        }
      },
    );
  }

  Widget _item(String url, String title, Function function) {
    return InkWell(
      onTap: () {
        function();
      },
      child: Column(
        children: [
          Divider(
            height: 1,
            indent: ScreenUtil().setHeight(15),
            color: AppColor.colorGrey245,
            thickness: ScreenUtil().setHeight(1),
            endIndent: ScreenUtil().setHeight(20),
          ),
          Container(
            color: Colors.white,
            padding: EdgeInsets.all(width(15)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  url,
                  width: width(18),
                  height: width(18),
                  fit: BoxFit.cover,
                ),
                Expanded(
                  flex: 1,
                  child: Container(
                    margin: EdgeInsets.only(left: 10),
                    child: Text(title,
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(15),
                            color: AppColor.colorDefaultText)),
                  ),
                ),
                Icon(
                  Icons.arrow_forward_ios,
                  color: AppColor.colorGrey153,
                  size: 16,
                ),
              ],
            ),
          ),
        ],
      ),
    );
    // return InkWell(
    //         onTap: () {
    //           Get.to(() => SettingsPage());
    //         },
    //         child: Container(
    //           alignment: Alignment.center,
    //           color: Colors.white,
    //           height: ScreenUtil().setHeight(55),
    //           child: ListTile(
    //             leading: Image.asset(
    //               "images/设置.png",
    //               width: 18.w,
    //               height: 18,
    //               fit: BoxFit.cover,
    //             ),
    //             title: Container(
    //               margin: EdgeInsets.only(left: ScreenUtil().setWidth(1)),
    //               child: Text(
    //                 "设置",
    //                 style: TextStyle(
    //                   fontSize: ScreenUtil().setSp(15),
    //                 ),
    //               ),
    //             ),
    //             trailing: Icon(Icons.keyboard_arrow_right),
    //           ),
    //         ),
    //       );
  }

  Widget _icon() {
    try {
      return IconButton(
        padding: EdgeInsets.only(right: ScreenUtil().setHeight(15)),
        onPressed: () {
          _selectAction();
        },
        icon: Image.asset(
          _userInfo.settings.sayHello == 0 || _userInfo.settings.sayHello == 1
              ? "images/ic_isopen_settings_green.png"
              : "images/ic_isopen_settings_gray.png",
          width: 24,
          height: 24,
        ),
        color: AppColor.colorTheme,
      );
    } catch (e) {
      return SizedBox();
    }
  }

  Container _userInfoWidget(V2TimUserFullInfo info) {
    return Container(
      color: Colors.white,
      child: Column(
        children: <Widget>[
          Align(
            alignment: Alignment.centerRight,
            child: _icon(),
          ),
          InkWell(
            onTap: () {

              try {
                Get.toNamed("/userInfoPage");
              } catch (e) {}
            },
            child: Row(
              children: <Widget>[
                Container(
                  child: HeadView(
                      (info.faceUrl != null && info.faceUrl.isEmpty)
                          ? HEADER_URL
                          : info.faceUrl,
                      ScreenUtil().setWidth(55),
                      ScreenUtil().setWidth(55)),
                  margin: EdgeInsets.only(
                    left: ScreenUtil().setWidth(15),
                  ),
                ),
                Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        // height: ScreenUtil().setHeight(28),
                        margin: EdgeInsets.only(
                          left: ScreenUtil().setWidth(10),
                        ),
                        alignment: Alignment.centerLeft,
                        child: Row(
                          children: [
                            Container(
                              child: Text(
                                info.nickName ?? "未设置昵称称",
                                style: TextStyle(
                                  fontSize: ScreenUtil().setSp(20),
                                  color: Color.fromRGBO(51, 51, 51, 1),
                                ),
                                softWrap: true,
                              ),
                              constraints: BoxConstraints(
                                maxWidth: MediaQuery.of(context).size.width / 2,
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(left: 6),
                              child: Image.asset(
                                info.gender == 2
                                    ? AppString.IMAGE_NV
                                    : AppString.IMAGE_NAN,
                                height: height(12),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(
                            left: ScreenUtil().setWidth(10),
                            top: ScreenUtil().setHeight(1)),
                        alignment: Alignment.centerLeft,
                        child: Text(
                          "自语ID：${getUserInfo().account.toString()}",
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(12),
                            color: Color.fromRGBO(153, 153, 153, 1),
                          ),
                          softWrap: true,
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: SizedBox(
                    width: 1,
                  ),
                  flex: 1,
                ),
                Container(
                  margin: EdgeInsets.only(),
                  child: Image.asset(
                    "images/ic_zxing.png",
                    width: width(12),
                    height: width(12),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(
                    right: width(15),
                    left: ScreenUtil().setWidth(0.2),
                  ),
                  child: Icon(Icons.keyboard_arrow_right),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 17),
            child: Divider(
              height: 1,
              indent: ScreenUtil().setHeight(80),
              color: Color.fromRGBO(248, 248, 248, 1),
              thickness: ScreenUtil().setHeight(1),
            ),
          ),
          // 签名
          Container(
            margin: EdgeInsets.only(
                left: ScreenUtil().setWidth(80),
                top: ScreenUtil().setHeight(10),
                bottom: ScreenUtil().setHeight(15),
                right: ScreenUtil().setWidth(15)),
            alignment: Alignment.centerLeft,
            child: Text(
              info.selfSignature != null ? "个性签名：${info.selfSignature}" : "",
              style: TextStyle(
                fontSize: ScreenUtil().setSp(12),
                color: Color.fromRGBO(51, 51, 51, 1),
              ),
              maxLines: 2,
              softWrap: true,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  ///修改是否忙碌
  void _changeOnline(bool _isOnLine) async {
    int sayHello = _userInfo.settings.sayHello;
    // print('---------修改前：$sayHello-------');

    switch (sayHello) {
      case 0:
        sayHello = _isOnLine ? 0 : 2;
        break;
      case 1:
        sayHello = _isOnLine ? 1 : 3;
        break;
      case 2:
        sayHello = _isOnLine ? 0 : 2;
        break;
      case 3:
        sayHello = _isOnLine ? 1 : 3;
        break;
    }
    // print('---------修改后：$sayHello-------');

    if (sayHello == _userInfo.settings.sayHello) return;

    var result = await SettingsDao.updateSettingsSayHello("sayHello", sayHello);
    if (result["resultCode"] != 1) {
      toast("修改失败：${result["resultCode"]}");
      return;
    }
    setState(() {
      _userInfo.settings.sayHello = sayHello;
      setUserinfoModel(_userInfo);
      print('--sayHello 修改后取值---${getUserSayHello()}');
    });
  }

  void _selectAction() async {
    int index = await showDialog(context: context, title: '修改状态');
    //1在线 2自动回复

    if (index == 1) {
      _changeOnline(true);
    }
    if (index == 2) {
      _changeOnline(false);
    }
  }

  Future<int> showDialog({
    @required BuildContext context,
    @required String title,
  }) {
    return showCustomBottomSheet(
        context: context,
        title: title,
        cancelTextColor: AppColor.colorDialog,
        children: [
          actionItem(
              context: context,
              index: 1,
              title: '在线',
              color: AppColor.colorDialog),
          actionItem(
              context: context,
              index: 2,
              title: '离开（自动回复）',
              isLastOne: true,
              color: AppColor.colorDialog),
        ]);
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  ///监听修改忙碌离线状态
  void _initEvent() {
    EventBus().addListener(EventKeys.EVENT_BUS_SETTINGS, (arg) {
      isOnline = arg;
    });
  }



  getHintDialog(BuildContext _context) {
    return CupertinoAlertDialog(
        content: new SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              Text(
                "提示",
                style:
                    TextStyle(fontSize: 13, color: AppColor.colorDefaultText),
              ),
              Text(
                AppString.bindingPhoneHint,
                style:
                    TextStyle(fontSize: 13, color: AppColor.colorDefaultText),
              ),
            ],
          ),
        ),
        actions: <Widget>[
          CupertinoDialogAction(
            child: Text(
              "取消",
              style: TextStyle(color: AppColor.colorGrey153),
            ),
            onPressed: () {
              Navigator.of(_context).pop();
            },
          ),
          CupertinoDialogAction(
            child: Text(
              "前去绑定",
              style: TextStyle(color: AppColor.colorTheme),
            ),
            onPressed: () {
              Get.to(BindPhonePage());
              Navigator.of(_context).pop();
            },
          ),
        ]);
  }
}
